package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Banner;
import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.query.BannerQuery;
import cn.wolfcode.wolf2w.respository.BannerRepository;
import cn.wolfcode.wolf2w.service.IBannerService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class BannerServiceImpl implements IBannerService {

    @Autowired
    private BannerRepository bannerRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Banner banner) {
        banner.setId(null);
        bannerRepository.save(banner);
    }

    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public Banner get(String id) {
        return bannerRepository.findById(id).orElse(null);
    }

    @Override
    public List<Banner> list() {
        return bannerRepository.findAll();
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {

        // MQL拼接语句
        Query query = new Query();

        // 分页对象 传入分页需要的参数 当前页-1  每页行数  排序规则  排序依据
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        // 返回分页对象
        // Page 是接口
        // PageImpl 是实现类
        return DBHelper.query(template, Banner.class, query, pageable);
    }

    @Override
    public void saveOrUpdate(Banner banner) {

        if (StringUtils.hasText(banner.getId())) {

            this.update(banner);
        } else {
            this.save(banner);
        }

    }

    @Override
    public List<Banner> queryBannerByType(int type) {

        // 前五篇
        // 排序
        Pageable pageable = PageRequest.of(0, 5, Sort.Direction.ASC, "sequence");
        // 类型
        // 状态
        return bannerRepository.findByTypeAndState(type, Banner.STATE_NORMAL, pageable);
    }
}


































































